import {computed, ref} from 'vue';
import { message } from 'ant-design-vue';
import api from "@/utils/api";

// 定义接口
export interface Role {
    id: number;
    name: string;
    createDate: string;
    updateDate: string;
    createUser: string;
    updateUser: string;
}

// 定义响应式变量
export const roleList = ref<Role[]>([]);
export const fetching = ref(false);
export const selectedRole = ref<any>(undefined);
export const selectedRoleObj = ref<any>(null);

export const newRoleName = ref();

export const isRoleNew = computed(() => {
    return (newRoleName && newRoleName.value!==undefined)
})


// 角色搜索方法
export const onRoleSearch = async (keyword: string, departmentName?: string) => {
    await fetchRoles(keyword, departmentName);
};

// 获取角色列表
export const fetchRoles = async (keyword: string = '', departmentName?: string) => {
    try {
        fetching.value = true;

        const response = await api.get('/role/dtoDepartmentRole', {
            params: {
                dpmNameCn: departmentName,
                name: keyword
            }
        });

        roleList.value = response.data;
        if(keyword.length>0){
            newRoleName.value = keyword;
        }
    } catch (error) {
        message.error('获取角色列表失败');
        console.error('获取角色列表失败:', error);
    } finally {
        fetching.value = false;
    }
};

// 角色焦点事件
export const onRoleFocus = (departmentName?: string) => {
    if (!departmentName) {
        message.warning('请先选择业务部门');
        return;
    }

    // 如果角色列表为空，调用空搜索
    if (roleList.value.length === 0) {
        fetchRoles('', departmentName);
    }
};

// 角色失焦事件
export const onRoleBlur = () => {
    // 检查当前输入的角色是否是新角色
    if (isRoleNew.value) {
        selectedRole.value = newRoleName.value;
    }
};

// 角色选择变化
export const onRoleChange = (value: any) => {
    selectedRoleObj.value = roleList.value.find(role =>
        role.id === value
    );

    if (selectedRoleObj.value) {
        newRoleName.value = undefined;
    }

    // 返回变化信息，用于清空相关数据
    return {
        roleCleared: true
    };
};

// 创建新角色
export const createNewRole = async (departmentId: number, roleName: string) => {
    try {
        fetching.value = true;

        await api.post('/role/departmentRole', {
            departmentId: departmentId,
            roleName: roleName,
        });

        // 重新获取角色列表以更新数据
        await fetchRoles(roleName);

        // 更新选中的角色对象
        selectedRoleObj.value = roleList.value.find(role =>
            role.name === roleName
        );
        newRoleName.value=undefined;

        message.success(`新角色【${roleName}】创建成功`);
        return true;
    } catch (error) {
        message.error('创建角色失败');
        console.error('创建角色失败:', error);
        return false;
    } finally {
        fetching.value = false;
    }
};

// 重置角色数据
export const resetRoleData = () => {
    selectedRole.value = '';
    selectedRoleObj.value = null;
    roleList.value = [];
    newRoleName.value = undefined;
};

// 导出所有方法
export default {
    roleList,
    fetching,
    selectedRole,
    selectedRoleObj,
    newRoleName,
    isRoleNew,
    onRoleSearch,
    fetchRoles,
    onRoleFocus,
    onRoleBlur,
    onRoleChange,
    createNewRole,
    resetRoleData
};